<template>
  <div class="main-page">
    <!-- 顶部导航栏 -->
    <el-header class="header-container fixed top-0 left-0 right-0 z-50">
      <!-- LOGO 和标题 -->
      <div class="logo-title">
        <img src="/imgs/admin/logo.png" alt="Logo" class="brand-logo">
        <span>
          <strong class="blue-bold">安心</strong><span>陪诊</span>
        </span>
      </div>

      <!-- 中间菜单项 - 修改后的菜单 -->
      <el-menu
          :default-active="activeIndex"
          mode="horizontal"
          @select="handleSelect"
          background-color="#fff"
          text-color="#555"
          active-text-color="#409EFF"
          class="escort-menu"
      >
        <el-menu-item index="0"><router-link to="/escortfirst">首页</router-link></el-menu-item>
        <el-menu-item index="1"><router-link to="/appointments">预约信息</router-link></el-menu-item>
        <el-menu-item index="2"><router-link to="/service-track">服务跟踪</router-link></el-menu-item>
        <el-menu-item index="3"><router-link to="/escort-reviews">用户评价</router-link></el-menu-item>
        <el-menu-item index="4"><router-link to="/escortfooter">陪诊员准则</router-link></el-menu-item>
        <el-menu-item index="5"><router-link to="/escortnotice">公告</router-link></el-menu-item>
      </el-menu>

      <!-- 右侧用户菜单 -->
      <div class="user-actions">
        <el-dropdown @command="handleUserCommand" trigger="click">
          <span class="dropdown-trigger">
            {{ userInfo.realName || '用户' }}
            <i class="el-icon-arrow-down el-dropdown__icon"></i>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>

    <!-- 主体布局 -->
    <el-container class="main-container">
      <!-- 左侧个人信息栏 -->
      <el-aside width="350px" class="aside-container">
        <div class="profile-section">
          <!-- 头像上传 -->
          <el-upload
              class="avatar-uploader"
              action="http://localhost:8080/v1/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"

          >
            <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>

          <h3 class="real-name">{{ userInfo.realName }}</h3>
          <p class="status">{{ userInfo.status === 'approved' ? '已通过审核' : '待审核' }}</p>
        </div>

        <!-- 基本信息卡片 -->
        <el-card class="basic-info-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
            </div>
          </template>
          <ul>
            <li><strong>陪诊员ID</strong>: {{ userInfo.id }}</li>
            <li><strong>真实姓名</strong>: {{ userInfo.realName }}</li>
            <li><strong>密码</strong>: {{ userInfo.password ? '******' : '未设置' }}</li>
            <li><strong>性别</strong>: {{ userInfo.gender === 'male' ? '男' : '女' }}</li>
            <li><strong>年龄</strong>: {{ userInfo.age }}</li>
            <li><strong>身份证号</strong>: {{ maskedIdCard }}</li>
            <li><strong>联系电话</strong>: {{ userInfo.phone }}</li>
            <li><strong>个人简介</strong>: {{ userInfo.profile }}</li>
          </ul>
        </el-card>

        <el-button
            type="primary"
            size="small"
            @click="openEditProfileDialog"
            class="edit-btn full-width-btn"
        >修改个人信息</el-button>

        <el-card class="stats-section" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>统计数据</span>
            </div>
          </template>
          <ul>
            <li>本月服务次数: <strong>{{ userInfo.serviceCount }}</strong></li>
            <li>
              平均评分:
              <el-rate v-model="userInfo.avgRating" disabled show-score text-color="#ff9900"></el-rate>
            </li>
          </ul>
        </el-card>
      </el-aside>

      <!-- 右侧主体内容 -->
      <el-main class="main-content">

        <!-- 默认显示日历组件 -->
        <div v-if="$route.name === 'EscortFirst'" class="default-calendar-section">
          <escort-first-view />
        </div>
        <!-- 子页面内容入口 -->
        <router-view />
      </el-main>
    </el-container>

    <!-- 修改个人信息弹窗 -->
    <edit-profile-dialog
        v-model="editDialogVisible"
        :user-info="userInfo"
        @update="handleUpdate"
    />
  </div>
</template>

<script>
import EditProfileDialog from '@/components/EditProfileDialog.vue'
import axios from '@/request/request.js'
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue'


export default {
  name: 'EscortHomeView',
  components: {
    EditProfileDialog,
    ArrowLeft,
    ArrowRight,
  },
  data() {
    return {
      activeIndex: '0',
      currentPageTitle: '首页',
      editDialogVisible: false,
      defaultAvatar: '/imgs/escort/default-avatar.jpg',
      tempAvatarUrl: null,
      hasUploaded: false,
      userInfo: {
        id: '',
        realName: '',
        phone: '',
        idCard: '',
        avatar: '',
        serviceCount: 0,
        avgRating: 0,
        status: '',
        gender: '',
        age: '',
        password: ''
      },
      currentDate: new Date(), // 单独提取避免嵌套在 userInfo 中
      appointments: [],
      loading: true,
      selectedDate: '', // 当前选中的日期
      selectedDateAppointments: [] // 当前选中日期的预约数据
    }
  },
  computed: {
    avatarSrc() {
      if (this.userInfo.avatar && !this.hasUploaded) {
        // 如果是数据库中保存的头像路径
        return this.userInfo.avatar;
      } else if (this.hasUploaded) {
        // 如果是刚上传的临时预览图
        return this.tempAvatarUrl;
      } else {
        // 默认头像
        return this.defaultAvatar;
      }
    },

    maskedIdCard() {
      const idCard = this.userInfo.idCard
      if (!idCard || idCard.length < 10) return idCard || '未设置'
      return idCard.slice(0, 3) + '*'.repeat(idCard.length - 7) + idCard.slice(-4)
    },
    currentMonth() {
      if (!this.currentDate) return ''
      return this.currentDate.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long'
      })
    }
  },
  methods: {

    handleSelect(key, keyPath) {
      console.log(key, keyPath)
      this.currentPageTitle = ['首页', '预约信息', '服务跟踪', '用户评价', '陪诊员准则'][key]; // 根据 key 更新页面标题
    },

    handleUserCommand(command) {
      if (command === 'logout') {
        this.logout(); // 调用 logout 方法
      }
    },
    async logout() {
      try {
        await this.$confirm('您确定要退出登录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        // 清除 token 和跳转
        localStorage.removeItem('token');
        this.$router.push('/login');
        this.$message.success('已退出登录');

      } catch (error) {
        this.$message.error('退出失败，请重试');
        console.error('Logout error:', error);
      }
    },
    async fetchAppointments(date) {
      try {
        const params = {
          month: this.currentDate.getMonth() + 1,
          year: this.currentDate.getFullYear()
        }
        if (date) {
          params.date = date
        }

        const res = await axios.get('/v1/escort/appointments', { params, withCredentials: true })
        if (res.data.state === 2000) {
          this.appointments = res.data.data || []
        }
      } catch (error) {
        console.error('获取预约数据失败:', error)
        this.appointments = []
      }
    },
    async fetchUserInfo() {
      try {
        const res = await axios.get('/v1/escort/info', { withCredentials: true })
        if (res.data.state === 2000) {
          this.userInfo = res.data.data
        } else {
          this.$message.error('获取信息失败')
          this.$router.push('/login')
        }
      } catch (error) {
        console.error(error)
        this.$message.error('未登录，请先登录')
        this.$router.push('/login')
      }
    },
    openEditProfileDialog() {
      this.editDialogVisible = true
    },
    handleUpdate(updatedInfo) {
      this.userInfo = updatedInfo
      this.editDialogVisible = false
    },
    handleAvatarSuccess(res, file) {
      const newAvatarUrl = res.data; // 假设后端返回了访问地址
      this.userInfo.avatar = newAvatarUrl;
      this.tempAvatarUrl = URL.createObjectURL(file.raw);
      console.log("1111:"+this.tempAvatarUrl)
      this.hasUploaded = true;
      // 可选：提交到后端保存用户头像
      // axios.post('http://localhost:8080/v1/upload').then(res => {
      //   console.log("123456:"+res.data.data)
      // });

    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }

      return isJPG && isLt2M
    },
    showAppointmentsForDate(dateStr) {
      const date = dateStr.split(' ')[0] // 去除时间部分
      this.selectedDate = date
      this.selectedDateAppointments = this.appointments.filter(app => app.date === date)
    }
  },
  watch: {
    '$route'(to) {
      this.currentPageTitle = to.meta.title || '未知页面'
    },
    currentDate() {
      this.fetchAppointments()
    }
  },
  created() {
    this.fetchUserInfo().finally(() => {
      this.loading = false
    })
    this.fetchAppointments()
  }
}
</script>

<style scoped>
.main-page{
  background-color:#f4f9fd;
}


/* 这里可以粘贴你的样式部分 */
.header-container {
  /*background-color: #ffffff;
  /*box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);*/
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.08);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30px;
  height: 70px;
  transition: all 0.3s ease-in-out;
}


.main-container {
  margin-top: 60px; /* 避开固定 header */
}

.logo-title {
  font-size: 20px;
  font-weight: normal;
  display: flex;
  align-items: center;
}

.brand-logo {
  width: 50px;
  height: 50px;
  margin-right: 15px;
}

.blue-bold {
  color: #409eff;
  /*font-weight: bold;*/
  font-weight: 600;
}
.escort-menu {
  flex: 1;
  display: flex;
  justify-content: center;
  border-bottom: none;
  margin: 0 20px;
}

.escort-menu .el-menu-item {
  padding: 0 20px;
  height: 70px;
  line-height: 70px;
  font-size: 16px;
  transition: all 0.3s;
  position: relative;
  border-bottom: 3px solid transparent;
}

.escort-menu .el-menu-item:hover {
  background-color: #f5f7fa;
  border-bottom-color: #c6e2ff;
}

.escort-menu .el-menu-item.is-active {
  border-bottom-color: #409eff;
  background-color: transparent;
}

.escort-menu .el-menu-item a {
  display: block;
  width: 100%;
  height: 100%;
  color: inherit;
  text-decoration: none;
}

.user-actions {
  gap: 20px;
}
.dropdown-trigger {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border-radius: 20px;
  transition: background-color 0.2s, transform 0.2s;
}
.dropdown-trigger:hover {
  background-color: #e6f2ff;
  transform: translateY(-2px);
}



.aside-container {
  /*background-color: #ffffff;*/
  background-color: #c4e2fb;
  /*box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);*/
  box-shadow: 4px 0 8px rgba(0, 0, 0, 0.05);
  height: 100%;
  padding: 30px;
  border-right: none;
}

.profile-section {
  text-align: center;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 30px;
  padding-bottom: 30px;
  /*background-color: #c4e2fb; /* 新增背景色 */
  padding-top: 20px; /* 可选：增加内边距让内容更居中 */
  border-radius: 8px; /* 可选：增加圆角使视觉更柔和 */
  border-bottom: none;
}

.aside-container {
  background-color: #ffffff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  height: 100%;
  padding: 20px;
  border-right: 1px solid #ebeef5;
}


.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 130px;
  height: 130px;
  background-color: #f5f5f5;
  transition: all 0.3s;
}

.avatar-uploader .el-upload :hover {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.avatar-uploader-icon {
  font-size: 36px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
}

.real-name {

  font-size: 18px;
  margin: 10px 0 0;
  margin-top: 15px;
  color: #333;
}

.status {
  font-size: 14px;
  color: #666;
  margin: 10px 0;
}

.edit-btn {
  width: 100%;
  margin-top: 10px;
  background-color: #409eff;
  border-color: #409eff;
}

.basic-info-card ul,
.stats-section ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.basic-info-card li,
.stats-section li {
  margin: 10px 0;
  font-size: 14px;
  color: #666;
}

.main-container {
  height: calc(100vh - 60px);
  background-color: #f5f5f5;
}

.main-content {
  padding: 20px;
}

.card-header {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.user-actions {
  display: flex;
  align-items: center;
}

.dropdown-trigger {
  cursor: pointer;
  padding: 8px 16px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.dropdown-trigger:hover {
  background-color: #f5f7fa;
}

.custom-calendar .el-calendar-table thead th {
  color: #409eff;
  font-weight: bold;
}
/* 右侧主体内容样式优化 */
.main-content {
  padding: 30px;
  min-height: calc(100vh - 130px);
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.08);
}
.default-calendar-section {
  margin-bottom: 30px;
}


/* 调整header布局 */
.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30px;
}

.logo-title {
  width: 200px;
}

.user-actions {
  width: 200px;
  display: flex;
  justify-content: flex-end;
}
</style>
